<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="600px"
  >
    <BasicForm @register="registerForm" />
    <BasicTable
      @register="registerMemberListTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { getDeptStaffs, getAllDutyStaff } from '/@/api/duty/dutystaff';
  import { addMemberFormSchema, memberListTableColumns } from './dutyschedule.data';
  import { setShiftMembers } from '/@/api/duty/dutySchedule';
  import { DutyScheduleSetMembersDto } from '/@/api/duty/model/dutyScheduleModel';
  import { getTeamByUserDept, getAllDutyTeam } from '/@/api/duty/dutyteam';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  import { useGlobSetting } from '/@/hooks/setting';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetDutyScheduleMembers',
    components: { BasicModal, BasicForm, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const MembersModuleName = inject<string>('MembersModuleName');

      //获取项目编码
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      console.log('项目编码', projectCode);

      //排班id
      const dataId = ref('');

      const [registerForm, { validate, resetFields, updateSchema }] = useForm({
        labelWidth: 80,
        schemas: addMemberFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [registerMemberListTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: '值班人员选择',
        api: projectCode.value != 'yzh' ? getAllDutyStaff : getDeptStaffs,
        columns: memberListTableColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        showIndexColumn: false,
        pagination: false, //关闭分页
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        clickToRowSelect: false, //开启点击行选中/取消checkbox
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        //接收排班ID
        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (MembersModuleName) {
          modalTitle.value = unref(MembersModuleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        if (projectCode.value === 'yzh') {
          getDutyTeamByUserDept();
        } else {
          getDutyTeam();
        }
      });

      /**
       * 查询用户所属部门的班值人员分组
       */
      function getDutyTeamByUserDept() {
        //班值人员选项集合
        let teamOptions = [];
        getTeamByUserDept()
          .then((res) => {
            console.log('res班值', res);
            res.forEach((team) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              teamOptions.push({ value: team.id, label: team.name });
            });

            //设班值人员下拉列表
            updateSchema({
              field: 'teamid',
              componentProps: {
                options: teamOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 查询所有班值人员分组
       */
      function getDutyTeam() {
        //班值人员选项集合
        let teamOptions = [];
        getAllDutyTeam()
          .then((res) => {
            console.log('res班值', res);
            res.forEach((team) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              teamOptions.push({ value: team.id, label: team.name });
            });

            //设班值人员下拉列表
            updateSchema({
              field: 'teamid',
              componentProps: {
                options: teamOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，设置值班成员
       */
      async function onButtonOkClick() {
        //获取选中的人员id集合
        let memberids = getSelectRowKeys();
        //获取表单数据
        const values = await validate();
        //查询条件
        let shiftMembers: DutyScheduleSetMembersDto = {
          id: dataId.value,
          teamid: values.teamid,
          staffids: memberids,
        };
        setModalProps({ confirmLoading: true });
        //调用接口进行保存
        setShiftMembers(shiftMembers)
          .then((res) => {
            if (!res || Object.keys(res).length == 0) {
              createMessage.success('设置成功', 2);
            }
            closeModal();
            emit('success');
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });

        setModalProps({ confirmLoading: false });

        //清空选中的行
        clearSelectedRowKeys();
      }

      return {
        op,
        modalTitle,
        MembersModuleName,
        registerModal,
        registerForm,
        registerMemberListTable,
        onButtonOkClick,
        getDutyTeamByUserDept,
        getDutyTeam,
      };
    },
  });
</script>
